﻿/* Copyright (C) 2007-2010 STS Soft

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; version 2 of the License.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA */

using System.IO;
using System.IO.Compression;
using STSdb.General.Collections;
using STSdb.General.Compression;

namespace STSdb.Persist
{
    public class DeflateIndexerPersist<T> : IIndexerPersist<T>
    {
        public readonly IIndexerPersist<T> persist;
        
        public DeflateIndexerPersist(IIndexerPersist<T> persist)
        {
            this.persist = persist;
        }
        
        #region IIndexerPersist<T> Members

        public void Store(BinaryWriter writer, IIndexer<T> values)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress, true))
                    persist.Store(new BinaryWriter(deflateStream), values);

                CountCompression.Serialize(writer, memoryStream.Length);
                writer.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
            }
        }

        public void Load(BinaryReader reader, IIndexer<T> values)
        {
            long length = CountCompression.Deserialize(reader);
            using (MemoryStream memoryStream = new MemoryStream(reader.ReadBytes((int)length)))
            {
                using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Decompress, true))
                    persist.Load(new BinaryReader(deflateStream), values);
            }
        }

        #endregion
    }
}
